<template>
  <div class="EchartArticle">
    <div ref="ArticleCharts" class="ArticleCharts"></div>
    <Coud></Coud>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, defineAsyncComponent } from 'vue'

import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TitleComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  ToolboxComponent,
  ToolboxComponentOption,
  LegendComponent,
  LegendComponentOption,
} from 'echarts/components'
import { PieChart, PieSeriesOption } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

//  引入标签云
const Coud = defineAsyncComponent(() => import('@/components/home/Coud.vue'))

echarts.use([
  TitleComponent,
  TooltipComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  LegendComponent,
  ToolboxComponent,
])

type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | TooltipComponentOption
  | PieSeriesOption
  | ToolboxComponentOption
  | LegendComponentOption
>
type chartsData = {
  name: string
  value: number
}
const props = defineProps<{
  HomeData: any[]
  labelData: any[]
}>()
const chartsData: chartsData[] =
  props.labelData &&
  props.labelData.map((item) => ({
    value: item.articleCount - 0,
    name: item.labelName,
  }))

const option: EChartsOption = {
  //  表格主体

  legend: {
    bottom: 0,
  },
  backgroundColor: '#fff',
  toolbox: {
    feature: {
      saveAsImage: { show: true },
    },
  },
  title: {
    text: `图书量(${props.HomeData[0].articleCount})`,
    left: 'center',
    top: 20,
    textStyle: {
      color: '#5470C6',
    },
  },

  tooltip: {
    trigger: 'item',
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: '55%',
      center: ['50%', '50%'],
      data: chartsData.sort(function (a, b) {
        return a.value - b.value
      }),
      roseType: 'radius',
      label: {
        show: true,
      },
      labelLine: {
        smooth: 0.2,
        length: 10,
        length2: 20,
      },
      itemStyle: {
        borderRadius: 8,
      },

      animationType: 'scale',
      animationEasing: 'elasticOut',
      animationDelay: function (idx) {
        return Math.random() * 200
      },
    },
  ],
}

const ArticleCharts = ref<HTMLDivElement>()

let myChart: echarts.ECharts | undefined
onMounted(() => {
  myChart = ArticleCharts.value && echarts.init(ArticleCharts.value)
  myChart && myChart.setOption(option)
  window.addEventListener('resize', resize)
})

function resize() {
  myChart && myChart.resize()
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', resize)
})
</script>

<style lang="scss" scoped>
.EchartArticle {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .ArticleCharts {
    width: 50%;
    height: 400px;
  }
}
</style>
